<template>
  <Modal
    v-model="form.visible"
    :width="1000"
    :mask-closable="false"
    :loading="loading"
    :title="form.data.id ? '修改发布信息' : '新增发布信息'"
    ok-text="提交"
    @on-ok="ok">
    <Row class="mt30">
      <Col>
        <Form ref="form" :model="form.data" :rules="ruleValidate" :label-width="80">
          <FormItem prop="newsTitle" label="标题">
            <Input v-model="form.data.newsTitle" placeholder="请输入"></Input>
          </FormItem>
          <FormItem prop="imagePath" label="封面图片">
            <upload-img v-if="form.visible" @on-change="onUploadImg" :defaultImageList="defaultImageList" :maxLength="1"></upload-img>
          </FormItem>
          <FormItem prop="newsTime" label="发布时间">
            <DatePicker type="datetime" style="width:100%" placeholder="选择时间" v-model="form.data.newsTime"></DatePicker>
          </FormItem>
          <FormItem prop="newsAuthor" label="作者">
            <Input v-model="form.data.newsAuthor" placeholder="请输入"></Input>
          </FormItem>
          <FormItem prop="newsSource" label="来源">
            <Input v-model="form.data.newsSource" placeholder="请输入"></Input>
          </FormItem>
          <FormItem prop="newsType" label="类型">
            <Select v-model="form.data.newsType" style="width: 100%" placeholder="请选择发布类型">
              <Option
                v-for="item in newsTypeCodeList"
                :key="item.code"
                :value="'' + item.code">{{ item.name }}</Option>
            </Select>
          </FormItem>
          <FormItem prop="status" label="是否发布">
            <RadioGroup v-model="form.data.status">
              <Radio :label="'0'">是</Radio>
              <Radio :label="'1'">否</Radio>
            </RadioGroup>
          </FormItem>
          <FormItem prop="newsContent" label="内容" class="mt50">
            <Row>
              <Col>
                <VueUEditor v-if="form.visible" ueditorPath='./static/ueditor-1.4.3.3/' @ready="editorReady" style="min-height: 300px"></VueUEditor>
              </Col>
            </Row>
          </FormItem>
        </Form>
      </Col>
    </Row>
  </Modal>
</template>

<script>
  import Vue from 'vue'
  import { mapGetters } from 'vuex'
  import VueUEditor from 'vue-ueditor'
  import uploadImg from '@/components/upload-img'
  import newsApi from '@/api/news'

  export default {
    name: 'update-modal',
    props: [
      'form'
    ],
    components: {
      VueUEditor,
      uploadImg
    },
    data () {
      return {
        loading: true,
        ruleValidate: {
          newsTitle: [
            { required: true, message: '请输入标题', trigger: 'change' },
            { max: 50, message: '标题字符长度应小于50', trigger: 'change' }
          ],
          imagePath: [
            { required: true, message: '请上传封面图片', trigger: 'change' }
          ],
          newsTime: [
            { required: true, type: 'date', message: '请选择发布时间', trigger: 'change' }
          ],
          newsAuthor: [
            { max: 20, message: '作者字符长度应小于20', trigger: 'change' }
          ],
          newsSource: [
            { max: 50, message: '来源字符长度应小于50', trigger: 'change' }
          ],
          newsType: [
            { required: true, message: '请选择类型', trigger: 'change' }
          ],
          newsContent: [
            { required: true, message: '请输入内容', trigger: 'change' }
          ]
        }
      }
    },
    computed: {
      ...mapGetters({
        userInfo: 'userInfo',
        newsTypeCodeList: 'newsTypeCodeList'
      })
    },
    watch: {
      'form.visible': 'onClose'
    },
    methods: {
      // 渲染编辑框
      editorReady (editorInstance) {
        editorInstance.setContent(this.form.data.newsContent || '')
        editorInstance.addListener('contentChange', () => {
          this.form.data.newsContent = editorInstance.getContent()
        })
      },
      ok () {
        this.$refs.form.validate((valid) => {
          if (valid) {
            this.submitForm()
          } else {
            this.$Message.error('表单验证失败，请检查输入项目!')
            this.form.visible = true
            this.loading = false
            setTimeout(() => {
              this.loading = true
            }, 100)
          }
        })
      },
      onClose (isVisible) {
        if (!isVisible) {
          this.$refs.form.resetFields()
        } else {
          this.defaultImageList = Vue.filter('splitImg')(this.form.data.imagePath || '')
        }
      },
      onUploadImg (imgList) {
        this.form.data.imagePath = imgList.filter((item) => {
          return item.name.length > 0
        }).map((item) => {
          if (item.response && item.response.responseData) {
            return item.response.responseData
          } else {
            return item.name
          }
        }).join(',')
        this.$refs.form.validateField('imagePath')
      },
      async submitForm () {
        let activityId = this.$route.params.activityId
        this.form.data.sourceId = activityId
        if (this.form.data.sourceId) {
          const { body } = await newsApi.update(this.form.data)
          if (this.$apiHelper.requestSuccessed(body.responseCode)) {
            this.$Message.info('修改成功')
            this.form.visible = false
            this.$emit('submit')
          } else {
            setTimeout(() => {
              this.$Modal.error({
                title: '错误',
                content: body.desc,
                onOk: () => {}
              })
            }, 500)
          }
        } else {
          const { body } = await newsApi.create(this.form.data)
          if (this.$apiHelper.requestSuccessed(body.responseCode)) {
            this.$Message.info('创建成功')
            this.form.visible = false
            this.$emit('submit')
          } else {
            setTimeout(() => {
              this.$Modal.error({
                title: '错误',
                content: body.desc,
                onOk: () => {}
              })
            }, 500)
          }
        }
      }
    },
    mounted () {
      this.$store.dispatch('getCode', 'news_type')
    }
  }
</script>
